import { _decorator, Component, Node, SpriteFrame, Vec2, Sprite, Label } from 'cc';
import { Context, UI } from '../Context';
import { UIManager } from '../UIManager';
import { item } from './item';
const { ccclass, property } = _decorator;

@ccclass('GameController')
export class GameController extends Component {
    @property(Node)
    grid: Node = null;
    @property(Node)
    reStart: Node = null;
    @property(Node)
    quit: Node = null;
    @property({ type: Array(SpriteFrame) })
    spriteFrames: Array<SpriteFrame> = [];
    @property(Node)
    selects: Node = null;
    @property(Label)
    score: Label = null;
    @property(Node)
    ending: Node = null;
    @property(Label)
    endingLabel: Label = null;

    grids: Array<Node> = [];
    sf_len: number = 0;
    selectArr: Array<SpriteFrame> = [];
    fruits: Array<number> = [];
    fruitCount: number = 0;
    private static instance: GameController = null;

    public static getInst() {
        if (this.instance == null) {
            console.error("GameController未正确挂载或意外销毁");
            return null;
        }
        return this.instance;
    }

    onLoad() {
        GameController.instance = this;
        this.grids = [];
        this.grid.children.forEach(ch => {
            this.grids.push(ch);
        })

        this.sf_len = this.spriteFrames.length;
        this.reStart.on("click", this.onClickStart, this);
        this.quit.on("click", this.onClickQuit, this);
    }

    start() {
        this.init();
    }

    /**
     * 初始化
     */
    init() {
        this.ending.active = false;
        this.initBottom();
        this.randomFruit();
        this.score.string = "0";

        for (let i = 0; i < this.grids.length; i++) {
            let childs: Array<Node> = this.grids[i].children;
            for (let j = 0; j < childs.length; j++) {
                const it: Node = childs[j].children[0];
                if (Context.grids[i][j]) {
                    let index: number = this.fruits.pop();
                    it.active = true;
                    let items: Array<item> = this.getChilds(i, j);

                    it.getComponent(item).init(this.spriteFrames[index], items);
                } else {
                    it.active = false;
                }
            }
        }
    }

    /**
     * 随机水果数组
     */
    randomFruit() {
        let count: number = 0;
        Context.grids.forEach(grid => {
            grid.forEach(val => {
                if (val)
                    count++;
            })
        });
        this.fruitCount = count;
        count /= 3;

        for (let i = 0; i < count; i++) {
            let index: number = Math.floor(Math.random() * this.sf_len);
            this.fruits.push(...[index, index, index]);
        }

        this.fruits.sort((a, b) => 0.5 - Math.random());
    }

    /**
     * 重试按钮
     */
    onClickStart() {
        this.init();
    }

    /**
     * 退出按钮
     */
    onClickQuit() {
        UIManager.getInst().show(UI.Home);
    }

    /**
     * 获取子节点
     * @param grid 
     * @param x 
     * @returns 
     */
    getChilds(grid: number, x: number): Array<item> {
        if (grid == 0)
            return [];

        const size: Vec2 = Context.grid_size;
        let childs: Array<Node> = this.grids[grid - 1].children;
        let result: Array<item> = [];
        result.push(this.getItem(childs[x]));
        if ((x >= size.x)) {
            result.push(this.getItem(childs[x - size.x]));
        }
        if ((x - size.x + 1) % size.x != 0) {
            result.push(this.getItem(childs[x - size.x + 1]));
        }
        if (x != size.x - 1) {
            result.push(this.getItem(childs[x + 1]));
        }
        return result;
    }

    /**
     * 获取item组件
     */
    getItem(nod: Node) {
        return nod.children[0].getComponent(item);
    }

    /**
     * 点击水果
     * @param sp 
     */
    selectFruit(sp_f: SpriteFrame) {
        let len: number = this.selectArr.length;
        const sp: Node = this.selects.children[len].getChildByName("Sprite");
        sp.active = true;
        sp.getComponent(Sprite).spriteFrame = sp_f;
        let sp_fs: Array<SpriteFrame> = this.selectArr.filter(val => val == sp_f);
        if (sp_fs.length < 2) {
            this.selectArr.push(sp_f);
        } else {
            this.selectArr = this.selectArr.filter(val => val != sp_f);
            this.refreshBottom();
            this.addScore();
        }

        if (this.selectArr.length >= Context.max_count) {
            this.endingLabel.string = "失败";
            this.ending.active = true;
        }else{
            this.fruitCount--;
            this.fruitCount == 0 && this.win();
        }
    }

    /**
     * 胜利
     */
    win(){
        this.endingLabel.string = "胜利";
        this.ending.active = true;
    }

    /**
     * 加分
     */
    addScore() {
        let score: number = parseInt(this.score.string);
        this.score.string = `${score += 100}`;
    }

    /**
     * 刷新底部
     */
    refreshBottom() {
        for (let i = 0; i < Context.max_count; i++) {
            const on_sp: Node = this.selects.children[i].getChildByName("Sprite");
            if (i < this.selectArr.length) {
                on_sp.active = true;
                on_sp.getComponent(Sprite).spriteFrame = this.selectArr[i];
            } else {
                on_sp.active = false;
            }
        }
    }

    /**
     * 初始化底部
     */
    initBottom() {
        this.selectArr = [];
        this.selects.children.forEach(target => {
            target.getChildByName("Sprite").active = false;
        })
    }
}


